

import React, { useState, useCallback } from 'react';
import { View, Text, TouchableOpacity, TextInput, FlatList, RefreshControl, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';
import ApprovalItem from './components/ApprovalItem';

interface ApprovalData {
  id: string;
  title: string;
  initiator: string;
  priority: 'high' | 'medium' | 'normal';
  createTime: string;
  currentNode: string;
  timeAgo: string;
}

const PENDING_APPROVAL_DATA: ApprovalData[] = [
  {
    id: 'proc-001',
    title: '员工请假申请 - 李小明',
    initiator: '李小明',
    priority: 'high',
    createTime: '2024-01-15 09:30',
    currentNode: '部门经理审批',
    timeAgo: '2小时前',
  },
  {
    id: 'proc-002',
    title: '采购申请单 - 办公设备',
    initiator: '王采购',
    priority: 'medium',
    createTime: '2024-01-15 14:20',
    currentNode: '财务审批',
    timeAgo: '1小时前',
  },
  {
    id: 'proc-003',
    title: '差旅报销申请 - 赵销售',
    initiator: '赵销售',
    priority: 'normal',
    createTime: '2024-01-14 16:45',
    currentNode: '部门经理审批',
    timeAgo: '昨天',
  },
  {
    id: 'proc-004',
    title: '合同审批 - 供应商合作协议',
    initiator: '刘法务',
    priority: 'high',
    createTime: '2024-01-14 11:20',
    currentNode: '总经理审批',
    timeAgo: '昨天',
  },
  {
    id: 'proc-005',
    title: '加班申请 - 周开发',
    initiator: '周开发',
    priority: 'medium',
    createTime: '2024-01-13 18:30',
    currentNode: '部门经理审批',
    timeAgo: '2天前',
  },
];

const PendingApprovalScreen: React.FC = () => {
  const router = useRouter();
  const [isSearchVisible, setIsSearchVisible] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedApprovalIds, setSelectedApprovalIds] = useState<Set<string>>(new Set());
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [approvalList, setApprovalList] = useState<ApprovalData[]>(PENDING_APPROVAL_DATA);

  const isBatchMode = selectedApprovalIds.size > 0;

  const handleSearchToggle = useCallback(() => {
    setIsSearchVisible(!isSearchVisible);
    if (isSearchVisible) {
      setSearchKeyword('');
    }
  }, [isSearchVisible]);

  const handleSearchClose = useCallback(() => {
    setIsSearchVisible(false);
    setSearchKeyword('');
  }, []);

  const handleFilterPress = useCallback(() => {
    // TODO: 实现筛选功能
    Alert.alert('筛选', '筛选功能开发中');
  }, []);

  const handleApprovalItemPress = useCallback((approvalId: string) => {
    if (!isBatchMode) {
      router.push(`/p-approval_detail?processInstanceId=${approvalId}`);
    }
  }, [isBatchMode, router]);

  const handleApprovalItemSelect = useCallback((approvalId: string, isSelected: boolean) => {
    setSelectedApprovalIds(prev => {
      const newSet = new Set(prev);
      if (isSelected) {
        newSet.add(approvalId);
      } else {
        newSet.delete(approvalId);
      }
      return newSet;
    });
  }, []);

  const handleSelectAll = useCallback((isSelectAll: boolean) => {
    if (isSelectAll) {
      setSelectedApprovalIds(new Set(approvalList.map(item => item.id)));
    } else {
      setSelectedApprovalIds(new Set());
    }
  }, [approvalList]);

  const handleCancelBatch = useCallback(() => {
    setSelectedApprovalIds(new Set());
  }, []);

  const handleBatchApprove = useCallback(() => {
    if (selectedApprovalIds.size === 0) return;
    
    Alert.alert(
      '批量操作',
      `确定要批量通过选中的 ${selectedApprovalIds.size} 项审批吗？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          onPress: () => {
            // TODO: 实现批量通过逻辑
            Alert.alert('成功', '批量通过成功');
            handleCancelBatch();
          },
        },
      ]
    );
  }, [selectedApprovalIds.size, handleCancelBatch]);

  const handleBatchReject = useCallback(() => {
    if (selectedApprovalIds.size === 0) return;
    
    Alert.alert(
      '批量操作',
      `确定要批量驳回选中的 ${selectedApprovalIds.size} 项审批吗？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          onPress: () => {
            // TODO: 实现批量驳回逻辑
            Alert.alert('成功', '批量驳回成功');
            handleCancelBatch();
          },
        },
      ]
    );
  }, [selectedApprovalIds.size, handleCancelBatch]);

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    try {
      // TODO: 实现刷新逻辑
      await new Promise(resolve => setTimeout(resolve, 1000));
      Alert.alert('成功', '刷新成功');
    } catch (error) {
      Alert.alert('错误', '刷新失败，请重试');
    } finally {
      setIsRefreshing(false);
    }
  }, []);

  const handleLoadMore = useCallback(async () => {
    if (isLoadingMore) return;
    
    setIsLoadingMore(true);
    try {
      // TODO: 实现加载更多逻辑
      await new Promise(resolve => setTimeout(resolve, 1000));
      Alert.alert('成功', '已加载更多数据');
    } catch (error) {
      Alert.alert('错误', '加载更多失败，请重试');
    } finally {
      setIsLoadingMore(false);
    }
  }, [isLoadingMore]);

  const isAllSelected = approvalList.length > 0 && selectedApprovalIds.size === approvalList.length;
  const isPartialSelected = selectedApprovalIds.size > 0 && selectedApprovalIds.size < approvalList.length;

  const renderApprovalItem = useCallback(({ item }: { item: ApprovalData }) => (
    <ApprovalItem
      approval={item}
      isSelected={selectedApprovalIds.has(item.id)}
      isBatchMode={isBatchMode}
      onPress={() => handleApprovalItemPress(item.id)}
      onSelect={(isSelected) => handleApprovalItemSelect(item.id, isSelected)}
    />
  ), [selectedApprovalIds, isBatchMode, handleApprovalItemPress, handleApprovalItemSelect]);

  const renderListHeader = useCallback(() => (
    <View style={styles.listHeaderContainer}>
      {/* 搜索框 */}
      {isSearchVisible && (
        <View style={styles.searchContainer}>
          <View style={styles.searchInputWrapper}>
            <FontAwesome6 name="magnifying-glass" style={styles.searchIcon} />
            <TextInput
              style={styles.searchInput}
              placeholder="搜索审批标题、发起人..."
              placeholderTextColor="#9CA3AF"
              value={searchKeyword}
              onChangeText={setSearchKeyword}
              autoFocus
            />
            <TouchableOpacity onPress={handleSearchClose} style={styles.searchCloseButton}>
              <FontAwesome6 name="xmark" style={styles.searchCloseIcon} />
            </TouchableOpacity>
          </View>
        </View>
      )}
    </View>
  ), [isSearchVisible, searchKeyword, handleSearchClose]);

  const renderListFooter = useCallback(() => (
    <View style={styles.listFooterContainer}>
      <TouchableOpacity
        style={styles.loadMoreButton}
        onPress={handleLoadMore}
        disabled={isLoadingMore}
      >
        {isLoadingMore ? (
          <View style={styles.loadingSpinner} />
        ) : (
          <View style={styles.loadMoreContent}>
            <FontAwesome6 name="arrow-down" style={styles.loadMoreIcon} />
            <Text style={styles.loadMoreText}>加载更多</Text>
          </View>
        )}
      </TouchableOpacity>
    </View>
  ), [isLoadingMore, handleLoadMore]);

  const renderEmptyState = useCallback(() => (
    <View style={styles.emptyStateContainer}>
      <FontAwesome6 name="inbox" style={styles.emptyStateIcon} />
      <Text style={styles.emptyStateTitle}>暂无待办审批</Text>
      <Text style={styles.emptyStateSubtitle}>您当前没有需要处理的审批任务</Text>
    </View>
  ), []);

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerTop}>
          <LinearGradient
            colors={['#6366f1', '#8b5cf6']}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.titleGradient}
          >
            <Text style={styles.title}>待我审批</Text>
          </LinearGradient>
          <View style={styles.headerActions}>
            <TouchableOpacity
              style={styles.headerActionButton}
              onPress={handleSearchToggle}
            >
              <FontAwesome6 name="magnifying-glass" style={styles.headerActionIcon} />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.headerActionButton}
              onPress={handleFilterPress}
            >
              <FontAwesome6 name="filter" style={styles.headerActionIcon} />
            </TouchableOpacity>
          </View>
        </View>
      </View>

      {/* 批量操作选择栏 */}
      {isBatchMode && (
        <View style={styles.batchSelectBar}>
          <View style={styles.batchSelectLeft}>
            <TouchableOpacity
              style={styles.selectAllCheckbox}
              onPress={() => handleSelectAll(!isAllSelected)}
            >
              <View style={[
                styles.checkboxInner,
                (isAllSelected || isPartialSelected) && styles.checkboxInnerSelected
              ]}>
                {isAllSelected && (
                  <FontAwesome6 name="check" style={styles.checkboxCheckIcon} />
                )}
                {isPartialSelected && !isAllSelected && (
                  <View style={styles.checkboxIndeterminate} />
                )}
              </View>
            </TouchableOpacity>
            <Text style={styles.selectedCountText}>
              已选择 {selectedApprovalIds.size} 项
            </Text>
          </View>
          <TouchableOpacity onPress={handleCancelBatch} style={styles.cancelBatchButton}>
            <FontAwesome6 name="xmark" style={styles.cancelBatchIcon} />
            <Text style={styles.cancelBatchText}>取消</Text>
          </TouchableOpacity>
        </View>
      )}

      {/* 主要内容区域 */}
      <FlatList
        data={approvalList}
        renderItem={renderApprovalItem}
        keyExtractor={(item) => item.id}
        ListHeaderComponent={renderListHeader}
        ListFooterComponent={renderListFooter}
        ListEmptyComponent={renderEmptyState}
        contentContainerStyle={styles.listContent}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            tintColor="#6366f1"
            colors={['#6366f1']}
          />
        }
      />

      {/* 批量操作底部栏 */}
      {isBatchMode && (
        <View style={styles.batchActions}>
          <TouchableOpacity
            style={[styles.batchActionButton, styles.approveButton]}
            onPress={handleBatchApprove}
          >
            <FontAwesome6 name="check" style={styles.batchActionIcon} />
            <Text style={styles.batchActionText}>批量通过</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.batchActionButton, styles.rejectButton]}
            onPress={handleBatchReject}
          >
            <FontAwesome6 name="xmark" style={styles.batchActionIcon} />
            <Text style={styles.batchActionText}>批量驳回</Text>
          </TouchableOpacity>
        </View>
      )}
    </SafeAreaView>
  );
};

export default PendingApprovalScreen;

